<template>
  <el-dialog v-model="visible" width="50%" destroy-on-close @close="handleClose" append-to-body draggable :loading="loading">
    <template #header>{{ TitleMap[dialogStatus] }}</template>
    <el-form ref="formRef" :model="modelForm" :rules="rules" label-width="80px" size="large" style="width: 95%">
      <el-form-item label="分类" prop="modelId">
        <el-select v-model="modelForm.modelId" placeholder="请选择分类">
          <el-option label="首页顶部" :value="1" />
          <el-option label="首页中部" :value="2" />
          <el-option label="首页底部" :value="3" />
          <el-option label="博客顶部" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="modelForm.title" />
      </el-form-item>
      <el-form-item label="链接" prop="link">
        <el-input v-model="modelForm.link" />
      </el-form-item>
      <el-form-item label="图片" prop="smallimg">
        <template v-if="isImg">
          <div class="flex flex-col items-center">
            <img class="app-blog-form-img" width="400" :src="modelForm.smallimg" alt="" />
            <div class="app-form-preview">
              <el-button size="default" type="danger" plain :icon="Delete" @click="handleDelImg">删除</el-button>
            </div>
          </div>
        </template>
        <template v-else>
          <el-upload ref="uploadRef" :action="state.action" :headers="state.uploadHeaders" :limit="3" list-type="picture-card" :multiple="false" :on-success="handleUploadSuccess" :on-preview="handleImgPreview" :on-remove="handleRemove">
            <i-ep-plus />
          </el-upload>
          <el-dialog v-model:visible="dialogVisible" append-to-body>
            <img width="100%" :src="modelForm.smallimg" alt="" />
          </el-dialog>
        </template>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit()">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import { APP_ID, TitleMap } from '@/config'
import { getToken } from '@/utils/auth'
import { cloneDeep } from 'lodash'
import { Delete } from '@element-plus/icons-vue'
// import { fetchFileUpload } from '@/api'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  setEditVisible: any
  categories: any
  models: any
  title?: string
  dialogStatus: string
}
const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    colPid: 0,
    ord: 0,
    title: '',
    description: '',
  },
  title: '',
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
  models: [],
})
const { modelForm }: any = toRefs(props)
const { loading, setLoading } = useLoading()
const formRef = ref<any>(null)
const uploadRef = ref<any>(null)
const visible = ref(false)
const dialogVisible = ref(false)
const apiUrl = import.meta.env.VITE_API_URL
const isImg = ref(false)
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  link: [{ required: true, message: '请输入链接', trigger: 'blur' }],
}
const state = reactive<any>({
  action: `${apiUrl}/api/file/upload`,
  uploadHeaders: { appid: APP_ID, Authorization: `Bearer ${getToken()}` },
})

watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)

// 监测上传状态
watch(
  () => modelForm.value.smallimg,
  (v) => {
    isImg.value = !!v
  }
)

const clearUploadFiles = () => {
  uploadRef.value?.clearFiles()
}

const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
  clearUploadFiles()
}

// 处理form数据
const handleForm = (form: any) => {
  return form
}

const handleSubmit = () => {
  formRef.value
    .validate((valid: any) => {
      if (!valid) return

      const data = unref(handleForm(cloneDeep(modelForm)))
      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)
      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })
}

const handleDelImg = () => {
  isImg.value = false
}

// 上传成功
const handleUploadSuccess = (response: any) => {
  if (response && response.data) {
    modelForm.value.smallimg = apiUrl + response.data
  }
}
const handleImgPreview = () => {
  dialogVisible.value = true
}
const handleRemove = () => {}
</script>
<style lang="scss"></style>
